<?PHP
session_start();
include_once "ini.php";
$id_cam = $_POST['id_cam'];
$message = $_POST['message'];

dbconnect();
$sql = "SELECT * FROM users WHERE id_user = '".$_SESSION['id_user']."';";
$requete = mysql_query($sql);
if (!$requete)
{
    echo "SQL error : ", $sql;
    exit ;
}
else
{
    while ($tab = mysql_fetch_assoc($requete))
    {
        $chat_online = $tab['chat'];
        $chat_people = split(":", $chat_online);
        $compteur = 0;
       
		if($chat_online == ""){
			
			 $chat_online = $id_cam;
		}
        else
        {
            for ($i = 0; $i < count($chat_people); $i++)
            {
                if ($chat_people[$i] == $id_cam)
                {
                    $compteur = 1;
                }
				
            }
			$chat_online = ($compteur == 0)?$chat_online.":".$id_cam:$chat_online;
			 
           
        }
       
		$query = "UPDATE `users` SET `chat` = '".$chat_online."' WHERE `users`.`id_user` = '".$_SESSION['id_user']."' LIMIT 1 ;";
        $result = mysql_query($query);
        if (!$result)
        {
            echo "SQL error : ", $query;
            exit ;
        }
        
    }
}

$sql = "SELECT * FROM users WHERE id_user = '".$id_cam."';";
$requete = mysql_query($sql);
if (!$requete)
{
    echo "SQL error : ", $sql;
    exit ;
}
else
{
    $tab = mysql_fetch_assoc($requete);
    $chat_online = $tab['chat'];
	$chat_people = split(":", $chat_online);
        $compteur = 0;
    if ($chat_inline != "")
    {echo "chat vide //";
        $chat_online .= ":".$_SESSION['id_user'];
    }
    else
    {
    	for ($i = 0; $i < count($chat_people); $i++)
            {
                if ($chat_people[$i] == $id_cam)
                {
                    $compteur = 1;
                }
				
            }
			$chat_online = ($compteur == 0)?$chat_online.":".$_SESSION['id_user']:$chat_online;
       
    }
	echo 'chat :'.$chat_online."//";
    $query = "UPDATE `users` SET `chat` = '".$chat_online."' WHERE `users`.`id_user` = '".$id_cam."' LIMIT 1 ;";
    $result = mysql_query($query);
    if (!$result)
    {
        echo "SQL error : ", $query;
        exit ;
    }
   
}

$correspondants = ($id_cam < $_SESSION['id_user'])?$id_cam.":".$_SESSION['id_user']:$_SESSION['id_user'].":".$id_cam;

$message = $_SESSION['login']." > ".$message;

$query = "INSERT INTO chat VALUES ('', '".$correspondants."', '".addslashes($message)."');";
$result = mysql_query($query);
if (!$result)
{
    echo "SQL error : ", $query;
    exit ;
}

dbclose();
?>
